<?
	require_once("db/db.php");
	
	header('Content-type: application/x-javascript');  // output as JSON

	// Get the connection string
	$XMLFile = "/home/assclap/config/real_estate.quickdata.config.xml"; //$_GET['XMLFile'];

	if(!isset($_GET['QueryID'])) 
		die("query failed\nQueryID not set");
	else
		$QueryID = $_GET['QueryID'];
	
	// Get the connection string
	$xml = simplexml_load_file($XMLFile);
	$Definition = $xml->xpath("//ConnectionString");
	$conn = (string)$Definition[0]['Value'];

	// Get the query fields	
	$Definition = $xml->xpath("//SearchQuery[@ID=\"{$QueryID}\"]");
	$FIELDS = (string)$Definition[0]['Fields'];
	$FROM = (string)$Definition[0]['From'];
	$fromStr = '';
	$WHERE = array();
	$whereStr = '';
	$ORDER_BY = (string)$Definition[0]['Order'];
	$CONJUNCTION = (string)$Definition[0]['Conjunction'];
	if(strlen($CONJUNCTION) == 0) $CONJUNCTION = 'AND';
	
	// Get the query parameters and replace the tokens 
	$Definition = $xml->xpath("//SearchQuery[@ID=\"{$QueryID}\"]/Parameter");
	for($i=0; $i < sizeof($Definition); $i++)
	{
		$field = (string)$Definition[$i]['id'];
		if(!isset($_GET[$field])) 
			die("Parameter \"$field\" defined in XML was not found in " . '$_GET');
		else
		{
			// addslashes protects against sql injection via closequotes
			$value = addslashes($_GET[$field]);
			if(strlen($value))
			{
				@$whereStr = (string)$Definition[$i]['whereStr'];
				@$fromStr = (string)$Definition[$i]['fromStr'];
				@$type = (string)$Definition[$i]['type'];
				@$condition = (string)$Definition[$i]['condition'];
				
				if(strlen($whereStr))
					if($type == 'array') {
						//it's an array, $value should be a comma seperated string
						if(strlen($value))
						{
							$condition = $condition ? " $condition " : " OR ";
							$valuelist = split(',', $value);
							$whereList = array();
							foreach ($valuelist as $value)
							{
								$whereList[] = str_replace('$' . $field . '$', $value, $whereStr);
							}
							$WHERE[] = ' (' . join($condition, $whereList) . ') ';
						}
					}
					else // It's just a regular string/numeric value
						$WHERE[] =  ' (' . str_replace('$' . $field . '$', $value, $whereStr)  . ') ';
						
				if(strlen($fromStr)) 
					$FROM .=  " $fromStr";
			}
		}
	}
	// Build the sql	
	$sql = "SELECT DISTINCT $FIELDS FROM $FROM";
	$sql .= (count($WHERE) ? " WHERE " . join(" $CONJUNCTION ", $WHERE) : '');
	
	// connect and grab the data
	$db = new DBConnection($conn);
	$r = $db->CreateQuery($sql);

	$objReturn = new QueryAndData();
	$objReturn->SQL = $sql;
	//$objReturn->Rows = $rows;

	
	while($row = $r->FetchObject())
		$objReturn->Rows[] = $row;


	// encode and return the data to a JSON object consumer
	//echo $json->encode($objReturn);
	echo json_encode($objReturn);
	//echo "\n/* sql: $sql */\n";
class QueryAndData
{
	public $SQL;
	public $Rows;
}
?>
